package com.ip.controller;

import com.ip.oss.IOssClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Controller
public class TestController {

    @Autowired
    IOssClient ossClient;

    @GetMapping("/helloWorld")
    @ResponseBody
    public String helloWorld() {
        return "helloWorld";
    }

    /**
     * 测试文件上传
     */
    @RequestMapping("testUpload")
    public void testUpload(MultipartFile multipartFile) throws Exception {
        byte[] file = multipartFile.getBytes();
        String oldName = multipartFile.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf(".") + 1);
        // 生成唯一文件名，当前时间 + 随机UUID + 文件类型
        String fName = UUID.randomUUID().toString() + "." + suffix;
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/";
        ossClient.uploadFile(file, dir, fName);
    }
}
